package com.example.ktdemo.blur.blurwidget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

/**
 * FileName: BlurAlignBottomView
 * Author: lzt
 * Date: 2023/5/10 11:30
 * 使用的时候，必须和模糊组件宽高一致，否则失效或错误
 */
public class BlurAlignBottomView extends View {
    private BlurAlignBottomBean mBlurInfo;

    private boolean mNeedDraw = false;


    public BlurAlignBottomView(Context context) {
        super(context);
    }

    public BlurAlignBottomView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public BlurAlignBottomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setBitmap(BlurAlignBottomBean info) {
        if (!info.check()) {
            return;
        }
        post(new Runnable() {
            @Override
            public void run() {
                BlurAlignBottomView.this.mNeedDraw = true;
                BlurAlignBottomView.this.mBlurInfo = info;
                postInvalidate();
            }
        });
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (this.mNeedDraw && mBlurInfo.getSrcBitmap() != null && !mBlurInfo.getSrcBitmap().isRecycled()) {
            this.mNeedDraw = false;
            int mesWidth = getMeasuredWidth();
            int mesHeight = getMeasuredHeight();
            float radius = mBlurInfo.getRadius();

            Bitmap mSrcBitmap = mBlurInfo.getSrcBitmap();

            canvas.save();

            canvas.clipRect(0, mesHeight - mBlurInfo.getBlurHeight(), mesWidth, mesHeight);

            RectF canvasRectF = new RectF(0, mesHeight - mBlurInfo.getBlurHeight(), mesWidth, mesHeight);
            Path mPath = new Path();
            mPath.addRoundRect(canvasRectF, radius, radius, Path.Direction.CW);
            canvas.clipPath(mPath);

            Rect bitmapRect = new Rect(0, 0, mesWidth, mesHeight);
            canvas.drawBitmap(mSrcBitmap, null, bitmapRect, null);


            canvas.restore();
        }
    }
}
